<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

use hg\apidoc\annotation as Apidoc;

/**
 * App\Models\AgentUser
 *
 * @property $id
 * @property $user_id
 * @property $username
 * @property $password
 * @property $avatar
 * @property mixed $text
 * @property \App\Models\User|null $user
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser query()
 * @mixin \Eloquent
 * @property string $money 可用余额
 * @property string $used_money 已提现余额
 * @property int $order_count 接单数量
 * @property string $wait_money 待结算金额
 * @property string|null $remember_token
 * @property int $pid 上级代理ID
 * @property int $province_id 省ID
 * @property int $city_ids 市ID组
 * @property int $city_id 市ID
 * @property int $district_ids 区ID组
 * @property int $type 0-市代理, 1-区代理
 * @property int $status
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereAvatar($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser wherePassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereRememberToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereShopId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereUsedMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereUsername($value)
 * @property int $cid 分类ID
 * @property string $name 门店名称
 * @property string $phone 门店电话
 * @property string $address 详细地址
 * @property string $longitude 经度
 * @property string $latitude 纬度
 * @property string $top_rate 门店每笔交易-上级用户分配比例
 * @property string $top_top_rate 门店每笔交易-上上级用户分配比例
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereImages($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereLatitude($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereLongitude($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser wherePhone($value)
 * @property int $district_id 区
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereCityId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereCityIds($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereDistrictId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereDistrictIds($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereProvinceId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|AgentUser whereType($value)
 */
class AgentUser extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'agent_users';

    protected $hidden = [
        'password'
    ];

    protected $casts = ['images'=>'json'];

    public static function booted()
    {


        self::creating(function (AgentUser $row){

        });

        self::created(function (AgentUser $row){
            //新增权限
            DB::table("agent_role_users")->insert([
                "role_id"=>1,"user_id"=>$row->id,'created_at'=>now()->toDateTimeLocalString(),
            ]);
        });


        self::deleting(function($row){
            DB::table("agent_role_users")->where(["role_id"=>1,"user_id"=>$row->id])->delete();
        });
    }

//    protected $appends = [
//        'text'
//    ];


    public static function getOptions(): Collection
    {
        return self::query()->orderByDesc("id")->pluck("name","id");
    }

//    public function getTextAttribute(){
//        return "账号:{$this->username}-【ID:{$this->user->id}】-{$this->user->nickname}";
//    }

    public function user(): HasOne
    {
        return $this->hasOne(User::class,"id","user_id");
    }

    public function top(): HasOne
    {
        return $this->hasOne(self::class,"id","pid");
    }

    /**
     * 代理商余额变更
     * @param int $type 类型 0=后台修改,1=订单金额,2=提现金额
     * @param int $agent_id 代理商ID
     * @param float $money 变更金额
     * @param string $remark 备注
     */
    public static function moneys(int $type, int $agent_id, float $money, string $remark){
        if ($money!=0){
            $agent = self::query()->where("id",$agent_id)->first();
            if ($agent){
                $pre_money = $agent->money;
                $after_money = $agent->money + $money;
                if ($type==2){
                    $used_money = $agent->used_money + abs($money);
                    $res = self::query()->where("id",$agent_id)->update(['money'=>$after_money,"used_money"=>$used_money]);
                }else{
                    $res = self::query()->where("id",$agent_id)->update(['money'=>$after_money]);
                }
                if ($res){
                    $data = [
                        'type'=>$type,
                        'user_id'=>$agent->user_id,
                        'agent_id'=>$agent_id,
                        'pre_money'=>$pre_money,
                        'money'=>$money,
                        'after_money'=>$after_money,
                        'remark'=>$remark
                    ];
                    AgentMoney::create($data);
                }
            }
        }
    }


    /**
     * @Apidoc\AddField("wait_money",type="float",default="0",desc="待结算金额")
     * @Apidoc\AddField("citys",type="array",default="",desc="所属城市")
     * @Apidoc\Returned(ref="App\Models\AgentUser")
     */
    public static function getDetail($user_id): AgentUser|null
    {
        $agent = self::whereUserId($user_id)->first();
        if ($agent){
            $cash_money = CashOrder::query()->where("status",0)->where("type",2)
                ->where("agent_id",$agent->id)->sum("amount");
            $agent->money = floatval($agent->money - $cash_money);
            $agent->wait_money = OrderCommission::query()->where("agent_id",$agent->id)
                ->where("is_settle",0)->sum('agent_money');
            $agent->money = number_format($agent->money,2);
        }
        return $agent;
    }
}
